import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:merchants/enum/spu_status.dart';
import 'package:merchants/models/spu.dart';
import 'package:merchants/providers/providers.dart';

class SpuListPage extends ConsumerStatefulWidget {
  const SpuListPage({super.key});

  @override
  SpuListPageState createState() => SpuListPageState();
}

class SpuListPageState extends ConsumerState<SpuListPage> {
  String? _selectedStatus;
  bool _sortByPriorityAscending = true;
  int _currentPage = 1;
  final int _pageSize = 20;
  bool _isLoading = false;
  bool _hasMoreData = true;
  List<Spu> _allSpus = [];
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _loadInitialData();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _refreshListData() {
    _loadInitialData();
  }

  void _filterByStatus(String? status) {
    setState(() {
      _selectedStatus = status;
    });
    _loadInitialData();
  }

  void _sortByPriority() {
    setState(() {
      _sortByPriorityAscending = !_sortByPriorityAscending;
      _allSpus.sort(
        (a, b) =>
            _sortByPriorityAscending
                ? a.priority.compareTo(b.priority)
                : b.priority.compareTo(a.priority),
      );
    });
  }

  Future<void> _toggleStatus(Spu spu) async {
    final confirm = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            title: const Text('确认操作'),
            content: Text(
              '确定要${spu.status == SpuStatus.enabled ? '下架' : '上架'} ${spu.name} 吗？',
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                child: Text('取消', style: TextStyle(color: Colors.grey[600])),
              ),
              TextButton(
                onPressed: () => Navigator.pop(context, true),
                child: Text(
                  '确定',
                  style: TextStyle(
                    color: Theme.of(context).primaryColor,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
    );

    if (confirm == true) {
      try {
        final newStatus =
            spu.status == SpuStatus.enabled
                ? SpuStatus.disabled
                : SpuStatus.enabled;

        final updatedSpu = Spu(
          id: spu.id,
          cate: spu.cate,
          swiperImages: spu.swiperImages,
          name: spu.name,
          detail: spu.detail,
          status: newStatus,
          priority: spu.priority,
          coverImage: spu.coverImage,
        );

        await ref.read(spuServiceProvider).updateSpu(updatedSpu);
        _refreshListData();

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                '${spu.name} 已${newStatus == SpuStatus.enabled ? '上架' : '下架'}',
              ),
              backgroundColor: Colors.green,
            ),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('操作失败: $e'), backgroundColor: Colors.red),
          );
        }
      }
    }
  }

  void _navigateToSpuDetail(String spuId) {
    context.go('/spu/$spuId');
  }

  // 加载初始数据
  Future<void> _loadInitialData() async {
    setState(() {
      _isLoading = true;
      _currentPage = 1;
      _allSpus = [];
      _hasMoreData = true;
    });

    try {
      final response = await ref.read(spuServiceProvider).getList(
        status: _selectedStatus,
        page: _currentPage,
        pageSize: _pageSize,
      );
      
      setState(() {
        _allSpus = response.records;
        _hasMoreData = response.hasNextPage;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载失败: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  // 加载更多数据
  Future<void> _loadMoreData() async {
    if (_isLoading || !_hasMoreData) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final response = await ref.read(spuServiceProvider).getList(
        status: _selectedStatus,
        page: _currentPage + 1,
        pageSize: _pageSize,
      );
      
      setState(() {
        _allSpus.addAll(response.records);
        _currentPage++;
        _hasMoreData = response.hasNextPage;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载更多失败: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  // 滚动监听
  void _onScroll() {
    if (_scrollController.position.pixels >= 
        _scrollController.position.maxScrollExtent - 200) {
      _loadMoreData();
    }
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    await _loadInitialData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('商品管理'),
        backgroundColor: Theme.of(context).primaryColor.withValues(alpha: 0.95),
        elevation: 2,
        centerTitle: true,
        automaticallyImplyLeading: false, // 禁用自动返回按钮
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => context.push('/tabs/spu/create'),
            tooltip: '添加商品',
            color: Colors.white,
          ),
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('筛选状态：', style: TextStyle(fontSize: 16)),
                DropdownButton<String?>(
                  value: _selectedStatus,
                  hint: const Text('全部'),
                  items: const [
                    DropdownMenuItem<String?>(value: null, child: Text('全部')),
                    DropdownMenuItem<String>(
                      value: 'ENABLED',
                      child: Text('已上架'),
                    ),
                    DropdownMenuItem<String>(
                      value: 'DISABLED',
                      child: Text('已下架'),
                    ),
                  ],
                  onChanged: _filterByStatus,
                ),
              ],
            ),
          ),
          Expanded(
            child: _isLoading && _allSpus.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : _allSpus.isEmpty
                    ? const Center(child: Text('暂无商品'))
                    : RefreshIndicator(
                        onRefresh: _onRefresh,
                        child: Column(
                          children: [
                            // 排序按钮
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 16.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  TextButton(
                                    onPressed: () => _sortByPriority(),
                                    child: Text(
                                      '按优先级 ${_sortByPriorityAscending ? '升序' : '降序'}',
                                      style: const TextStyle(
                                        color: Color(0xFF1A73E8),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            // 商品列表
                            Expanded(
                              child: ListView.builder(
                                controller: _scrollController,
                                itemCount: _allSpus.length + (_hasMoreData ? 1 : 0),
                                itemBuilder: (context, index) {
                                  // 加载更多指示器
                                  if (index == _allSpus.length) {
                                    return Container(
                                      padding: const EdgeInsets.all(16.0),
                                      child: const Center(
                                        child: CircularProgressIndicator(),
                                      ),
                                    );
                                  }

                                  final spu = _allSpus[index];
                                  return Card(
                                    margin: const EdgeInsets.symmetric(
                                      vertical: 8,
                                      horizontal: 16,
                                    ),
                                    elevation: 2,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(16),
                                    ),
                                    child: ListTile(
                                      title: Text(spu.name),
                                      subtitle: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            '状态: ${spu.status == SpuStatus.enabled ? '已上架' : '已下架'}',
                                            style: TextStyle(
                                              color:
                                                  spu.status == SpuStatus.enabled
                                                      ? Colors.green
                                                      : Colors.red,
                                            ),
                                          ),
                                          Text('分类数: ${spu.cate.length}'),
                                        ],
                                      ),
                                      onTap: () => _navigateToSpuDetail(spu.id!),
                                      trailing: Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          IconButton(
                                            icon: Icon(
                                              spu.status == SpuStatus.enabled
                                                  ? Icons.arrow_downward
                                                  : Icons.arrow_upward,
                                              color:
                                                  spu.status == SpuStatus.enabled
                                                      ? Colors.red
                                                      : Colors.green,
                                            ),
                                            onPressed: () => _toggleStatus(spu),
                                            tooltip:
                                                spu.status == SpuStatus.enabled
                                                    ? '下架'
                                                    : '上架',
                                          ),
                                          IconButton(
                                            icon: const Icon(
                                              Icons.edit,
                                              color: Color(0xFF1A73E8),
                                            ),
                                            onPressed: () {
                                              final id = spu.id;
                                              final route = '/tabs/spu/form/$id';
                                              context.go(route);
                                            },
                                            tooltip: '编辑',
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
          ),
        ],
      ),
    );
  }
}
